package cn.matezk.cloud.framework.typeHandler;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public abstract class AbstractArrayTypeHandler<T> extends BaseTypeHandler<List<T>> {
    private static ObjectMapper objectMapper;


    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {

        }
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.wasNull() ? null : readList(rs.getString(columnName), specificType());
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.wasNull() ? null : readList(rs.getString(columnIndex), specificType());
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.wasNull() ? null : readList(cs.getString(columnIndex), specificType());
    }

    public static <T> List<T> readList(String json, TypeReference<List<T>> tTypeReference) {
        if (json == null || "".equals(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json,tTypeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract TypeReference<List<T>> specificType();
}